import net.miginfocom.swing.MigLayout;
import parser.Parser;
import parser.prestige.AbstractNode;
import parser.prestige.MeldunekParser;
import parser.prestige.TechnologiaParser;
import parser.prestige.technologia.xml.BomItem;
import parser.prestige.technologia.xml.Technologia;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: marcin.kaluza
 * Date: 29.11.13
 * Time: 09:22
 * To change this template use File | Settings | File Templates.
 */
public class ToXmlParser extends JFrame {
    private Parser parser;
    private String input;
    private String output;
    private String directoryI;
    private String directoryO;

    private JTextField inputTF, outputTF, productCode, technologyName;
    private JButton confirmB, clearB;
    private JTable scrollTable;
    private JPanel scrollPanel;

    private List<AbstractNode> nodes;

    private static int LAYOUT_WIDTH = 300;
    private static int LAYOUT_HEIGHT = 400;
    private static int LAYOUT_COLUMN_GAP = 5;
    private static String LAYOUT_COLUMNS_MIG_LAYOUT_CONSTRAINTS = "";
    private static String LAYOUT_ROWS_MIG_LAYOUT_CONSTRAINTS = "";
    /**
     * Wywoływana gdy program zostanie wywołany bez argumentów. Pokazuje użytkownikowi GUI z ręcznym wyborem
     * pliku wejsciowego.
     */
    private void showGui() {
        System.out.println("Show GUI");
        //TODO: inicjalizacja i pokazanie GUI
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(LAYOUT_WIDTH, LAYOUT_HEIGHT);
        LAYOUT_COLUMNS_MIG_LAYOUT_CONSTRAINTS = "["+LAYOUT_WIDTH/4+"]"+"["+LAYOUT_WIDTH/4+"]"+"["+LAYOUT_WIDTH/4+"]"+"["+LAYOUT_WIDTH/4+"]";

        inputTF = new JTextField("InputFile");
        inputTF.setEditable(false);
        outputTF = new JTextField("OutputFile");
        outputTF.setEditable(false);

        final JButton startB = new JButton("Parse");
        startB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startB.setEnabled(false);
                scrollTable.setEnabled(true);
                if (output == null) {
                    initializeParser(new String[]{directoryI + "\\" + input});
                } else {
                    initializeParser(new String[] {directoryI+"\\"+input, directoryO+"\\"+output});
                }
            }
        });
        startB.setEnabled(false);
        JButton inputB = new JButton("Input");
        inputB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
                int resp = jfc.showOpenDialog(ToXmlParser.this);
                if (resp == JFileChooser.APPROVE_OPTION) {
                    input =  jfc.getSelectedFile().getName();
                    directoryI = jfc.getCurrentDirectory().toString();
                    inputTF.setText(directoryI+"\\"+input);
                    startB.setEnabled(true);
                }
            }
        });
        JButton outputB = new JButton("Output");
        outputB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
                int resp = jfc.showSaveDialog(ToXmlParser.this);
                if (resp == JFileChooser.APPROVE_OPTION) {
                    if (jfc.getSelectedFile().getAbsolutePath().endsWith(".xml")) {
                        output = jfc.getSelectedFile().getName();
                    } else {
                        output = jfc.getSelectedFile().getName() + ".xml";
                    }
                    directoryO = jfc.getCurrentDirectory().toString();
                    outputTF.setText(directoryO + "\\" + output);
                }
            }
        });
        confirmB = new JButton("Confirm save");
        confirmB.setEnabled(false);
        confirmB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                confirmB.setEnabled(false);
                inputTF.setText("InputFile");
                outputTF.setText("OutputFile");
                scrollTable.setEnabled(false);

                Technologia tech = (Technologia) nodes.get(0);

                tech.setIndeks(productCode.getText());
                tech.getOperacje().get(0).setProduktTechIndeks(productCode.getText());
                tech.getOperacje().get(0).getProduktTech().setIndeks(productCode.getText());

                tech.setNazwa(technologyName.getText());
                tech.getOperacje().get(0).setProduktTechNazwa(technologyName.getText());
                tech.getOperacje().get(0).getProduktTech().setNazwa(technologyName.getText());

                List<BomItem> items = tech.getOperacje().get(0).getItems();
                //wypisz bomitemy
                for (int j = 0; j < scrollTable.getModel().getRowCount(); j++) {
                    items.get(j).setIndeks((String) scrollTable.getModel().getValueAt(j, 0));
                    items.get(j).setNazwa((String) scrollTable.getModel().getValueAt(j, 1));
                }

                parser.writeOutput(nodes);
            }
        });
        clearB = new JButton("Clear Names");
        clearB.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < scrollTable.getModel().getRowCount(); i++) {
                    scrollTable.getModel().setValueAt("",i,1);
                }
                scrollTable.revalidate();
                scrollTable.repaint();
//                ((DefaultTableModel)scrollTable.getModel()).fireTableDataChanged();
            }
        });

        productCode = new JTextField();
        technologyName = new JTextField();
        scrollTable = new JTable(0, 2);
        scrollTable.getColumnModel().getColumn(0).setPreferredWidth(Math.round(LAYOUT_WIDTH*0.25f));
        scrollTable.getColumnModel().getColumn(1).setPreferredWidth(Math.round(LAYOUT_WIDTH*0.75f));
        scrollTable.setEnabled(false);

        //mig layout
        MigLayout layout = new MigLayout("wrap 4",LAYOUT_COLUMNS_MIG_LAYOUT_CONSTRAINTS,LAYOUT_ROWS_MIG_LAYOUT_CONSTRAINTS);
//        MigLayout layout = new MigLayout("wrap 4","","");

        JPanel panel = new JPanel(layout);
        //wiersz 0
        panel.add(inputTF, "cell 0 0 3 1, grow 100");
        panel.add(inputB, "cell 3 0 1 1,growx");
        //wiersz 1
        panel.add(outputTF, "cell 0 1 3 1, grow 100");
        panel.add(outputB, "cell 3 1 1 1, growx");
        //wiersz 2
        panel.add(startB, "cell 0 2 2 1, growx");
        panel.add(confirmB, "cell 2 2 2 1, growx");
        //wiersz 3
        panel.add(new JSeparator(JSeparator.HORIZONTAL), "cell 0 3 4 1, grow");
        //wiersz 4
        panel.add(new JLabel("Kod produktu:"), "cell 0 4 2 1, align right");
        panel.add(productCode, "cell 2 4 2 1, grow");
        //wiersz 5
        panel.add(new JLabel("Nazwa technologii:"), "cell 0 5 2 1, alignx right");
        panel.add(technologyName, "cell 2 5 2 1, grow");
        //wiersz 6
        panel.add(new JSeparator(JSeparator.HORIZONTAL), "cell 0 6 4 1, grow");
        //wiersz 7
        scrollPanel = new JPanel(new MigLayout("height :200:, width :300:","",""));
        scrollPanel.add(new JScrollPane(scrollTable));
        panel.add(scrollPanel,"cell 0 7 4 4");
        //wiersz 8
        panel.add(clearB,"cell 0 11 4 4, grow 100");

        this.add(panel);

        setVisible(true);
        setResizable(false);
    }

    /**
     * Wypelnia formularz danymi z parsera
     */
    private void fillFormWithDataFromParser() {
        confirmB.setEnabled(true);
        Technologia technologia = (Technologia) nodes.get(0);
        productCode.setText(technologia.getIndeks());
        technologyName.setText(technologia.getNazwa());

        scrollPanel.remove(0);

        //wypisanie BomItemow
        List<BomItem> items = technologia.getOperacje().get(0).getItems();
//        scrollTable = new JTable(items.size(), 2);
        String[][] data = new String[items.size()][2];
        for (int i = 0; i < items.size(); i++) {
            data[i][0] = items.get(i).getIndeks();
            data[i][1] = items.get(i).getNazwa();
        }
        scrollTable = new JTable(data, new String[]{"Index", "Name"});
        Dimension tableSize = scrollPanel.getPreferredSize();
        scrollTable.getColumnModel().getColumn(0).setPreferredWidth(Math.round(tableSize.width*0.25f));
        scrollTable.getColumnModel().getColumn(1).setPreferredWidth(Math.round(tableSize.width*0.75f));

        scrollPanel.add(new JScrollPane(scrollTable));
        scrollPanel.revalidate();
        scrollPanel.repaint();
    }

    /**
     * Inicjalizuje odpowiedni parser w zależności od typu pliku wejściowego
     * @param files nazwa pliku wejściowego i opcjonalnie nazwa wyjściowego
     */
    private void initializeParser(String[] files) {
        if ((parser = getParser(files[0])) == null) {
            //Parser nie znaleziony
            //TODO: dorobic info o braku parsera
            System.exit(0);
        }
        //sprawdzic czy podano nazwę wyjściową
        if (files.length > 1) {
            nodes = parser.readInput(files[0], files[1]);
        } else {
            nodes = parser.readInput(files[0]);
        }
        fillFormWithDataFromParser();
    }

    /**
     * Zwraca obiekt Parser zależny od rodzaju rozszerzenia pliku wejściowego
     * @param file plik wejściowy
     * @return odpowiedni obiekt Parser
     */
    private Parser getParser(String file) {
//        String[] splitted = file.split("\\.");
//        String extension = splitted[splitted.length-1];
//        if (extension.equalsIgnoreCase("TXT")) {
//            return new MeldunekParser();
//        }
//        return null;
        return new TechnologiaParser();
    }

    public static void main(String... args){
        ToXmlParser parserMain = new ToXmlParser();
        if(args != null && args.length > 0 && args.length <= 2) {//bez GUI
            parserMain.initializeParser(args);
        }else{//wywołaj GUI
            System.out.println("Using: java ToXmlParser <InputFileName> [<OutputFileName>]");
            parserMain.showGui();
        }
    }
}
